package solutions.leetcode.normal;

import solutions.lib.BaseSolution;

import java.awt.*;

/**
 * @author lizhidong
 * <a href="https://leetcode-cn.com/problems/rectangle-area/">223. 矩形面积</a>
 */
public class Solution223 extends BaseSolution {

    public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
        // 交集计算的方法是，上边/右边取最小的，下边/左边取最大的，上-下 / 右-左 后取不小于0，相乘后即为交集面积
        return (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) - (
                Math.max(0, Math.min(ax2, bx2) - Math.max(ax1, bx1))
                        * Math.max(0, Math.min(ay2, by2) - Math.max(ay2, by2))
        );
    }

    /*
    这里是另外一种方法计算交集的方法，麻烦些
    public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
        int intersize;
        if (bx1 >= ax2 || ax1 >= bx2 || ay1 >= by2 || by1 >= ay2) {
            intersize = 0;
        } else {
            intersize = (by2 - by1 + Math.min(0, by1 - ay1) + Math.min(0, ay2 - by2))
                    * (bx2 - bx1 + Math.min(0, bx1 - ax1) + Math.min(0, ax2 - bx2));
        }
        return (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) - intersize;
    }
     */

    public static void main(String[] args) {
        Solution223 solution = new Solution223();
        System.out.println(solution.computeArea(
                -2,
                -2,
                2,
                2,
                3,
                3,
                4,
                4
        ));
    }
}
